﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;

namespace KMSFanHome2.Services
{
    public class ElegantRoute:Route
    {
        //包含了控制器和actionresult
        public static readonly string[] ToElegant = new[] { "controller", "action" };

        //构造方法，继承了基类的构造方法
        public ElegantRoute(string url,RouteValueDictionary defaults,RouteValueDictionary constraints,RouteValueDictionary dataTokens,IRouteHandler routeHandler):base(url,defaults,constraints,dataTokens,routeHandler) { }

        /// <summary>
        /// 虚方法，用来重写Route的方法
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var result = base.GetRouteData(httpContext);
            if (result == null) { return null; }
            foreach (var key in ToElegant)
            {
                HandleItems(result.Values, key, StringElegantHelper.Elegant);
            }

            return result;
        }

        /// <summary>
        /// 虚方法，覆盖Route里的GetVirtualPath方法
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            var elegantValue = new RouteValueDictionary(values);
            foreach (var key in ToElegant)
            {
                HandleItems(elegantValue, key, StringElegantHelper.Elegant);
            }

            return base.GetVirtualPath(requestContext, elegantValue);
        }


        /// <summary>
        /// 处理类函数
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="key"></param>
        /// <param name="handler"></param>
        private void HandleItems(RouteValueDictionary dict,string key,Func<string,string> handler)
        {
            if (!dict.ContainsKey(key))
            {
                return;
            }

            var value = dict[key];
            if (!(value is string)) { return; }
            dict[key] = handler(value as string);

        
        }

    }

    /// <summary>
    /// ElegantRoute扩展类
    /// </summary>
    public static class ElegantRouteExtensions
    {
        public static ElegantRoute MapElegantRoute(this RouteCollection routes, string name, string url, object defaults)
        {
            var route = new ElegantRoute(url,new RouteValueDictionary(defaults),
                new RouteValueDictionary(),
                new RouteValueDictionary(),
                new MvcRouteHandler());

            routes.Add(name, route);
            return route;
        }

    
    }
}